# -*- coding:utf-8 -*-
import re
import Earthquake
import time
import json
import common
import requests
import mysql.connector
from bs4 import BeautifulSoup


class GetData:
    def __init__(self, url):
        self.Url = url
        res = requests.get(url)
        res.encoding = 'utf-8'
        self.SourceCode = res.text
        self.QuakeData = []

    def save_to_database(self):
        config = common.get_config()
        conn = mysql.connector.connect(
            host=config['host'],
            user=config['user'],
            passwd=config['password'],
            database=config['database'],
            port=config['port'],
            buffered=True
        )
        cursor = conn.cursor()
        for item in self.QuakeData:
            cursor.execute('SELECT * FROM Item WHERE DataSources = {} And Time = "{}" AND Longitude = {} AND Latitude = {};'.format(item.DataSources, item.Time, item.Longitude, item.Latitude))
            if cursor.fetchall():
                continue
            item.set_address()
            sql = 'INSERT INTO Item(DataSources, CreateTime, Time, Level, Depth, Longitude, Latitude, Location, Address, Country, Province, City, District, Town, CountryCode, CityCode, CityLevel, TownCode, AdCode)'
            sql += "VALUES (" + str(item.DataSources)
            t = time.localtime(time.time())
            sql += ", '" + '{}-{}-{} {}:{}:{}'.format(str(t[0]).zfill(4), str(t[1]).zfill(2), str(t[2]).zfill(2), str(t[3]).zfill(2), str(t[4]).zfill(2), str(t[5]).zfill(2))
            sql += "', '" + item.Time
            sql += "', " + str(item.Level)
            sql += ", " + str(item.Depth)
            sql += ", " + str(item.Longitude)
            sql += ", " + str(item.Latitude)
            sql += ", '" + item.Location.replace("'", "''")
            sql += "', '" + item.Address.replace("'", "''")
            sql += "', '" + item.Country.replace("'", "''")
            sql += "', '" + item.Province.replace("'", "''")
            sql += "', '" + item.City.replace("'", "''")
            sql += "', '" + item.District.replace("'", "''")
            sql += "', '" + item.Town.replace("'", "''")
            sql += "', " + str(item.CountryCode)
            sql += ", " + str(item.CityCode)
            sql += ", " + str(item.CityLevel)
            sql += ", '" + item.TownCode
            sql += "', '" + item.AdCode + "');"
            cursor.execute(sql)
        cursor.close()
        conn.commit()
        conn.close()


class GetChinaData(GetData):
    def __init__(self, url):
        super().__init__(url)
        data = json.loads(self.SourceCode[1:-1])
        for i in data['shuju']:
            self.QuakeData.append(Earthquake.Earthquake(0, i['O_TIME'], eval(i['M']), i['EPI_DEPTH'], eval(i['EPI_LON']), eval(i['EPI_LAT']), i['LOCATION_C']))


class GetUSAData(GetData):
    def __init__(self, url):
        super().__init__(url)
        data = json.loads(self.SourceCode)
        for i in data['features']:
            if i['geometry']['type'] == 'Point':
                t = time.localtime(i['properties']['time'] / 1000)
                time_str = '{}-{}-{} {}:{}:{}'.format(str(t[0]).zfill(4), str(t[1]).zfill(2), str(t[2]).zfill(2), str(t[3]).zfill(2), str(t[4]).zfill(2), str(t[5]).zfill(2))
                self.QuakeData.append(Earthquake.Earthquake(1, time_str, i['properties']['mag'], i['geometry']['coordinates'][2], i['geometry']['coordinates'][0], i['geometry']['coordinates'][1], i['properties']['place']))


class GetEuropeData(GetData):
    def __init__(self, url):
        super().__init__(url)
        for i in BeautifulSoup(self.SourceCode, features='html.parser').find_all('table')[4].find('tbody').find_all('tr'):
            row = i.find_all('td')
            if len(row) < 13:
                continue
            t = time.localtime(time.mktime(time.strptime(row[3].find('a').text[:-2], "%Y-%m-%d %H:%M:%S")) + 8 * 60 * 60)
            time_str = '{}-{}-{} {}:{}:{}'.format(str(t[0]).zfill(4), str(t[1]).zfill(2), str(t[2]).zfill(2), str(t[3]).zfill(2), str(t[4]).zfill(2), str(t[5]).zfill(2))
            lat = eval(re.search('(\d+\.?\d*)', row[4].text).group(1))
            lon = eval(re.search('(\d+\.?\d*)', row[6].text).group(1))
            level = eval(re.search('(\d+\.?\d*)', row[10].text).group(1))
            depth = eval(re.search('(\d+\.?\d*)', row[8].text).group(1))
            if 's' in row[5].text.lower():
                lat = -lat
            if 'w' in row[7].text.lower():
                lon = -lon
            self.QuakeData.append(Earthquake.Earthquake(2, time_str, level, depth, lon, lat, row[11].text))


class GetChinaDataRecent(GetData):
    def __init__(self, url):
        super().__init__(url)
        for i in BeautifulSoup(self.SourceCode, features='html.parser').find('table').find_all('tr')[1:]:
            row = i.find_all('td')
            self.QuakeData.append(Earthquake.Earthquake(0, row[1].text, eval(row[0].text), eval(row[4].text), eval(row[3].text), eval(row[2].text), row[5].text))
